package com.cloud.drore.eboss.operation.service.impl;

import com.cloud.drore.eboos.common.base.*;
import com.cloud.drore.eboos.common.entity.base.DictionaryVo;
import com.cloud.drore.eboos.common.entity.base.UserInfo;
import com.cloud.drore.eboos.common.entity.operation.po.FinaceSourseDataCommonPo;
import com.cloud.drore.eboos.common.entity.operation.vo.FinaceSourseDataListVo;
import com.cloud.drore.eboos.common.entity.operation.vo.FinaceSourseDataVo;
import com.cloud.drore.eboos.common.entity.operation.vo.FinaceSourseDistributorDataVo;
import com.cloud.drore.eboos.common.entity.supplier.vo.FinaceSupplierIncomeDetailsVo;
import com.cloud.drore.eboos.common.util.LocalData;
import com.cloud.drore.eboos.exception.BusinessException;
import com.cloud.drore.eboss.operation.entity.FinaceSourseDataOperation;
import com.cloud.drore.eboss.operation.entity.po.DictionaryOrderPo;
import com.cloud.drore.eboss.operation.mapper.FinaceOperationMapper;
import com.cloud.drore.eboss.operation.mapper.MerchantMapper;
import com.cloud.drore.eboss.operation.service.IBaseDataFeign;
import com.cloud.drore.eboss.operation.service.IFeignFinace;
import com.cloud.drore.eboss.operation.service.IFinaceService;
import com.cloud.drore.eboss.operation.service.IFinaceSettlementHistoryService;
import com.cloud.drore.eboss.supplier.entity.po.FinaceSupplierIncomeDetailsPo;
import com.cloud.drore.eboss.supplier.entity.vo.ProductQueryVo;
import com.cloud.drore.eboss.supplier.mapper.ProductConsumeRelationMapper;
import com.cloud.drore.eboss.supplier.operationApiService.IProductRelationOperationApiService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 浙江卓锐科技股份有限公司 版权所有 © Copyright 2018<br>
 *
 * @Description: 分销商订单查询财务相关信息<br>
 * @Project: eboos <br>
 * @CreateDate: Created in 2018/1/4 12:45 <br>
 * @Author: <a href="410508961@qq.com">夏凯</a>
 */
@Service
public class FinaceFormOperationServiceImpl extends BaseServiceImpl implements IFinaceService {

    @Resource
    IFeignFinace iFeignFinace;
    @Autowired
    FinaceOperationMapper finaceOperationMapper;


    @Autowired
    IProductRelationOperationApiService iProductRelationOperationApiService;
    @Autowired
    IBaseDataFeign iBaseDataFeign;

    @Autowired
    IFinaceSettlementHistoryService iFinaceSettlementHistoryService;
    @Autowired
    MerchantMapper merchantMapper;
    @Resource
    ProductConsumeRelationMapper productConsumeRelationMapper;

    @Override
    public MyMapper getMapper() {
        return finaceOperationMapper;
    }

    private static final int OPERATION_FEGIN_SERVICE_SUCCESS_CODE = 8200;

    /**
     * @param finaceSourseDataCommonPo
     * @ClassName: FinaceOperationServiceImpl
     * @Return: com.cloud.drore.eboos.common.base.ResultMessage
     * @Decription: 查询得到自动结算报表信息同时将处理好的数据进行批量插入，远程调用去拿信息
     * @CreateDate: Created in 2018/1/29 0029 下午 5:39
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public ResultMessage finaceSourseDataOperationList(List<FinaceSourseDataCommonPo> finaceSourseDataCommonPo) {
        //远程调用拿到分销商那边运算过得数据信息
        ResultMessage<FinaceSourseDataListVo> finaceSourseDataOperationDealer =
                iFeignFinace.getFinaceFormList(finaceSourseDataCommonPo);
        if (finaceSourseDataOperationDealer.getCode() != OPERATION_FEGIN_SERVICE_SUCCESS_CODE) {
            throw new RuntimeException("远程调用订单产品表获取信息失败！");
        }
        //供应商报表
        List<FinaceSourseDataVo> finaceSourseDataOperationList =
                finaceSourseDataOperationDealer.getData().getSupplierList();
        //分销商报表
        List<FinaceSourseDistributorDataVo> finaceSourseDataDealerList =
                finaceSourseDataOperationDealer.getData().getDistributorList();

        if (null == finaceSourseDataOperationList || "".equals(finaceSourseDataOperationList)
                || null == finaceSourseDataDealerList || "".equals(finaceSourseDataDealerList)) {
            Object message = finaceSourseDataOperationDealer.getMessage();
            throw new RuntimeException(message.toString());
        }
        return finaceSourseDataOperationDealer;
    }


    /**
     * @param id
     * @ClassName: FinaceOperationServiceImpl
     * @Return: com.cloud.drore.eboos.common.base.ResultMessage<com.cloud.drore.eboss.operation.entity.FinaceSourseDataOperation>
     * @Decription: 通过供应商id查询产品编号
     * @CreateDate: Created in 2018/1/29 0029 下午 4:59
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public ResultMessage<List<ProductQueryVo>> findProductNum(Long id) {
        //公共产品的id
        List<ProductQueryVo> productIdList = productConsumeRelationMapper.queryProductList(id);
        // List<ProductQueryVo> productIdList = iProductRelationOperationApiService.selectProductIdBySupplierId(id);
        return new ResultMessage(productIdList);
    }

    /**
     * @param page
     * @ClassName: FinaceOperationServiceImpl
     * @Return: com.cloud.drore.eboos.common.base.ResultMessage<com.cloud.drore.eboss.operation.entity.FinaceSourseDataOperation>
     * @Decription: 通过分销商id和产品编号搜索相关数据报表（供应商使用）
     * @CreateDate: Created in 2018/1/30 0030 上午 11:05
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public ResultMessage<FinaceSourseDataOperation> queryFinaceFormListByChoice(PagePo<FinaceSourseDataOperation> page) throws BusinessException {
        // 设置查找的属性
        FinaceSourseDataOperation finaceSourseDataOperation = page.getFields();
        //需要追加供应商的数据来源
        UserInfo currentUser = LocalData.getCurrentUser();
        finaceSourseDataOperation.setSupplierId(currentUser.getTypeId());
        //供应商和运营商公用的sql查询，主要是负责加载查询条件
        Example example = differenceIdentity(finaceSourseDataOperation);
        PageHelper.startPage(page);
        List<FinaceSourseDataVo> FinaceSourseDataOperationList = finaceOperationMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo<>(FinaceSourseDataOperationList);
        return ResultMessage.success(pageInfo);
    }

    /**
     * @param page
     * @ClassName: FinaceOperationServiceImpl
     * @Return: com.cloud.drore.eboos.common.base.ResultMessage<com.cloud.drore.eboss.operation.entity.FinaceSourseDataOperation>
     * @Decription: 通过分销商id和产品编号搜索相关数据报表（分销商商使用）
     * @CreateDate: Created in 2018/1/30 0030 上午 11:05
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public ResultMessage<FinaceSourseDataOperation> queryOperationFinaceFormListByChoice(PagePo<FinaceSourseDataOperation> page) throws BusinessException {

        // 设置查找的属性
        FinaceSourseDataOperation finaceSourseDataOperation = page.getFields();

        //供应商和运营商公用的sql查询，主要是负责加载查询条件
        Example example = differenceIdentity(finaceSourseDataOperation);

        PageHelper.startPage(page);
        List<FinaceSourseDataVo> FinaceSourseDataOperationList = finaceOperationMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo<>(FinaceSourseDataOperationList);
        return ResultMessage.success(pageInfo);
    }

    /**
     * @param finaceSourseDataOperation
     * @ClassName: FinaceFormOperationServiceImpl
     * @Return: tk.mybatis.mapper.entity.Example
     * @Decription: 主要是用来区别供应商还是运营商来调用结算记录的接口，存在供应商传输的数据的历史条件
     * @CreateDate: Created in 2018/2/9 0009 下午 5:00
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public Example differenceIdentity(FinaceSourseDataOperation finaceSourseDataOperation) throws BusinessException {

        Example finaceSourseDataOperationExample = new Example(FinaceSourseDataOperation.class);
        Example.Criteria criteria = finaceSourseDataOperationExample.createCriteria();
        //分销商id
        if (!(null == finaceSourseDataOperation.getDistributorId() || "".equals(finaceSourseDataOperation.getDistributorId()))) {
            criteria.andEqualTo("distributorId", finaceSourseDataOperation.getDistributorId());
        }
        //供应商id
        if (!(null == finaceSourseDataOperation.getSupplierId() || "".equals(finaceSourseDataOperation.getSupplierId()))) {
            criteria.andEqualTo("supplierId", finaceSourseDataOperation.getSupplierId());
        }
        //产品编号
        if (StringUtils.isNotEmpty(finaceSourseDataOperation.getProductNum())) {
            criteria.andEqualTo("productNum", finaceSourseDataOperation.getProductNum());
        }
        //产品历史记录表的id
        if (!(null == finaceSourseDataOperation.getFinaceSettlementHistoryId() || "".equals(finaceSourseDataOperation.getFinaceSettlementHistoryId()))) {
            criteria.andEqualTo("finaceSettlementHistoryId", finaceSourseDataOperation.getFinaceSettlementHistoryId());
        } else {
            throw new RuntimeException("对不起，没有相关数据信息，请求非法");
        }
        return finaceSourseDataOperationExample;
    }

    /**
     * @param page
     * @ClassName: FinaceFormOperationServiceImpl
     * @Return: com.cloud.drore.eboos.common.base.ResultMessage
     * @Decription: 远程调用拿到分销商那边供应商查询财务管理收入明细
     * @CreateDate: Created in 2018/3/5 0005 下午 9:28
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public ResultMessage<List<FinaceSupplierIncomeDetailsVo>> feginOperationFinaceIncomeDetailList(PagePo<FinaceSupplierIncomeDetailsPo> page) throws BusinessException {
       // UserInfo currentUser = LocalData.getCurrentUser();
        //page.getFields().setSupplierId(currentUser.getTypeId());
        //收入明细查询的时候条件判断
        FinaceSupplierIncomeDetailsPo fields = page.getFields();
        //这里也只是上传的供应商那边的结算单价
        judgeParametersIsNull(fields.getSupplierSettlementPrice());
        judgeParametersIsNull(fields.getSettlementStartTime());
        judgeParametersIsNull(fields.getSettlementEndTime());
        judgeParametersIsNull(fields.getProductNum());
        //judgeParametersIsNull(fields.getDistributorId());

        //远程调用拿到分销商那边供应商查询财务管理收入明细
        ResultMessage<List<FinaceSupplierIncomeDetailsVo>> feginOperationFinaceIncomeDetailDealer = iFeignFinace.getOperationFinaceIncomeDetailList(page);
        if (feginOperationFinaceIncomeDetailDealer.getCode() != OPERATION_FEGIN_SERVICE_SUCCESS_CODE) {
            throw new RuntimeException("远程调用或取收入明细信息失败！");
        }
        PageHelper.startPage(page);
        List<FinaceSupplierIncomeDetailsVo> feginOperationFinaceIncomeDetailDealerList = feginOperationFinaceIncomeDetailDealer.getData();
        PageInfo pageInfo = new PageInfo<>(feginOperationFinaceIncomeDetailDealerList);
        pageInfo.setTotal(feginOperationFinaceIncomeDetailDealer.getTotal());
        return ResultMessage.success(pageInfo);
    }

    /**
     * @param param
     * @ClassName: FinaceFormOperationServiceImpl
     * @Return: void
     * @Decription: 校验参数是否为空
     * @CreateDate: Created in 2018/2/10 0010 下午 5:25
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public void judgeParametersIsNull(Object param) throws BusinessException {

        if (null == param || "".equals(param)) {
            throw new RuntimeException("缺少必须要上传的参数！");
        }
    }

    /**
     * @param
     * @ClassName: FinaceFormOperationServiceImpl
     * @Return: com.cloud.drore.eboos.common.base.ResultMessage
     * @Decription: 供应商版本查询收入明细初始化订单状态
     * @CreateDate: Created in 2018/3/5 0005 下午 9:29
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public ResultMessage<List<DictionaryOrderPo>> queryOrderStatusList() {
        List<DictionaryVo> orderStatusList = iBaseDataFeign.getDicListMapByCodeVo("ORDER_STATUS");
        List<DictionaryOrderPo> collect = orderStatusList.stream().filter(dictionary -> Integer.parseInt(dictionary.getDicCode()) >= 16)
                .map(dictionaryVo -> {
                    DictionaryOrderPo dictionaryOrderPo = new DictionaryOrderPo();
                    dictionaryOrderPo.setDicCode(Integer.parseInt(dictionaryVo.getDicCode()));
                    dictionaryOrderPo.setName(dictionaryVo.getName());
                    return dictionaryOrderPo;
                }).collect(Collectors.toList());
        return ResultMessage.success(collect);
    }
}
